from PySide2.QtWidgets import QApplication, QWidget, QHBoxLayout
import sys
from PySide2.QtCharts import QtCharts
from PySide2.QtGui import QPainter, QPen, QColor
from PySide2.QtCore import Qt
import openpyxl

class ShowPage(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(1200, 500)
        self.chart = QtCharts.QChart()  # 图
        self.chartview = QtCharts.QChartView(self.chart) # 图层
        self.series = QtCharts.QPieSeries()  #数据
        self.series2 = QtCharts.QPieSeries()  # 数据
        self.wb = openpyxl.load_workbook('C:\\Users\\zuozh\\Desktop\\太原科大Python综合培训\\国家数据\\人口\\人口年龄结构和抚养比.xlsx')
        self.ws = self.wb['年度数据']
        self.buildChart()

    def buildChart(self):
        self.series.setName('2018年人口年龄结构')
        for i in range(5, 8):
            self.series.append(
                str(self.ws.cell(row=i, column=1).value) + '-' + str(self.ws.cell(row=i, column=2).value),
                float(self.ws.cell(row=i, column=2).value)
            )
        self.series.setHoleSize(0.5)    # 孔大小
        self.series.setHorizontalPosition(0.3)  # 水平位置
        # 指示
        self.series.setLabelsPosition(
            QtCharts.QPieSlice.LabelOutside)
        self.series.setLabelsVisible(True)

        self.series2.setName('2018年抚养比')
        for i in range(9, 11):
            self.series2.append(
                str(self.ws.cell(row=i, column=1).value) + '-' + str(self.ws.cell(row=i, column=2).value),
                float(self.ws.cell(row=i, column=2).value)
            )
        self.series2.setHoleSize(0.0)  # 孔大小
        self.series2.setHorizontalPosition(0.7)  # 水平位置
        # 指示
        self.series2.setLabelsPosition(QtCharts.QPieSlice.LabelOutside)
        self.series2.setLabelsVisible(True)

        sl1 = self.series.slices()[2]
        sl1.setExploded()   # 切片是否与饼图分离
        sl1.setLabelVisible(True)
        sl1.setPen(QPen(QColor('blue'), 1, Qt.SolidLine))
        sl1.setBrush(Qt.gray)                    # 整体颜色
        sl1.setLabelColor(QColor(0, 0, 255))  # 字体颜色

        self.chart.setTitle('饼图示例')
        self.chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations)    # 动画
        # self.chart.legend().hide()  # 隐藏图例
        self.chart.addSeries(self.series)   # 输入数据
        self.chart.addSeries(self.series2)  # 输入数据
        layout = QHBoxLayout()
        layout.addWidget(self.chartview)
        self.setLayout(layout)
        self.chartview.setRenderHint(QPainter.Antialiasing) # 防止变形

if __name__ == "__main__":
    app = QApplication(sys.argv)
    v = ShowPage()
    v.show()
    sys.exit(app.exec_())
